package com.yc.services;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yc.config.SearchAiConfig;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeUtility;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;
import java.util.Properties;
@Service
public class ToolServices {
    @Tool("求多个数的和")
    public int add(int...nums) {
        int total = 0;
        for (int num : nums) {
            total += num;
        }
        System.out.println("total = " + total);
        return total;
    }
    @Tool("求一个字符串的长度")
    public int length(String str) {
        System.out.println("length = " + str.length());
        return str.length();
    }

    @Tool("计算一个数的平方根")
    public double sqrt(double num) {
        System.out.println("sqrt = " + Math.sqrt(num));
        return Math.sqrt(num);
    }

    // 温度单位的枚举类
    public enum TemperatureUnit {
        CELSIUS, FAHRENHEIT, KELVIN
    }

    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class WeatherResponse {
        @JsonProperty("results")
        public List<WeatherData> results;

        @JsonIgnoreProperties(ignoreUnknown = true)
        public static class WeatherData {
            @JsonProperty("location")
            @JsonIgnoreProperties(ignoreUnknown = true)
            public Location location;

            @JsonProperty("now")
            @JsonIgnoreProperties(ignoreUnknown = true)
            public Now now;

            @JsonIgnoreProperties(ignoreUnknown = true)
            public static class Location {
                @JsonProperty("name")
                public String name;
                // 其他字段会被自动忽略
            }

            @JsonIgnoreProperties(ignoreUnknown = true)
            public static class Now {
                @JsonProperty("text")
                public String text;
                @JsonProperty("temperature")
                public String temperature;
                @JsonProperty("code")  // 新增code字段
                public String code;  // 虽然不使用但需要定义
            }
        }
    }

//    @Tool("用户会询问某个城市的天气,他还会给你温度单位，请返回城市的天气情况")
//    public String getWeather(
//            @P("城市名称") String city,
//            @P("温度单位") TemperatureUnit unit
//    ) {
//        try {
//            String apiKey = "SlUbsQwIT-x7oPyEC";
//            String url = String.format(
//                    "https://api.seniverse.com/v3/weather/now.json?key=%s&location=%s&language=zh-Hans&unit=c",
//                    apiKey, URLEncoder.encode(city, "UTF-8")
//            );
//
//            HttpClient client = HttpClient.newHttpClient();
//            HttpRequest request = HttpRequest.newBuilder()
//                    .uri(URI.create(url))
//                    .timeout(Duration.ofSeconds(10))
//                    .build();
//
//            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
//            String json = response.body();
//
//            ObjectMapper mapper = new ObjectMapper();
//            WeatherResponse weatherResponse = mapper.readValue(json, WeatherResponse.class);
//
//            WeatherResponse.WeatherData.Now now = weatherResponse.results.get(0).now;
//            return String.format("%s的天气：%s，气温 %s°C", city, now.text, now.temperature);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return "获取天气失败：" + e.getMessage();
//        }
//    }

    @Tool("发送邮件")
    public String sendEmail(
            @P("收件人邮箱") String to,
            @P("邮件主题") String subject,
            @P("邮件内容") String content
    ) throws MessagingException {
        // 1. QQ邮箱SMTP配置
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.qq.com");          // QQ邮箱SMTP服务器
        props.put("mail.smtp.port", "465");                  // SSL加密端口
        props.put("mail.smtp.auth", "true");                 // 启用认证
        props.put("mail.smtp.ssl.enable", "true");           // 启用SSL加密
        props.put("mail.smtp.ssl.protocols", "TLSv1.2");     // 指定协议版本

        // 2. 认证信息（使用授权码而非密码）
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(
                        "2873208363@qq.com",
                        "dnnsxkfrpfezdejc" // 这里是您的授权码
                );
            }
        };

        // 3. 创建会话
        Session session = Session.getInstance(props, authenticator);
        session.setDebug(true); // 打印调试日志

        try {
            // 4. 构建邮件
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress("2873208363@qq.com")); // 必须与认证邮箱一致
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

            // 处理中文主题编码
            message.setSubject(MimeUtility.encodeText(subject, "UTF-8", "B"));

            // 设置HTML内容
            message.setContent(content, "text/html; charset=utf-8");

            // 5. 发送邮件
            Transport.send(message);
            return "邮件发送成功至: " + to;
        } catch (Exception e) {
            throw new MessagingException("邮件发送失败: " + e.getMessage(), e);
        }
    }

}
